﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;
using System.Data;
using System.Data.SqlClient;

public partial class User_Shares_ProjectsDetails : System.Web.UI.Page
{

    #region Property
    private int _TotalPages;


    public int TotalPages
    {
        get { return _TotalPages; }
        set
        {
            _TotalPages = value;
            Session["TotalPages"] = value;
        }
    }


    private int _CurrentPage;


    public int CurrentPage
    {
        get { return _CurrentPage; }
        set
        {
            Session["PageIndex"] = value;
            _CurrentPage = value;
        }
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            var thisUser = HttpContext.Current.User;
            if (thisUser.Identity.IsAuthenticated)
            {
                if (!Page.IsPostBack)
                {
                    GridView gridView = LoginViewSearch.FindControl("GridViewProjects") as GridView;
                    if ( gridView != null )
                        //This part of code never executes.
                        Session["TotalPages"] = Business.ProjectDetails.GetTotalPageCountOfContracts(gridView.PageSize, true, true).ToString();
                    else
                    {
                        Session["TotalPages"] = Business.ProjectDetails.GetTotalPageCountOfContracts(50 , true, true).ToString();
                    }
                    Session["PageIndex"] = 0;
                    CurrentPage = Convert.ToInt32(Session["PageIndex"]);
                    TotalPages = Convert.ToInt32(Session["TotalPages"]);
                }
                PopulateGrid(thisUser);

                CurrentPage = Convert.ToInt32(Session["PageIndex"]);
                TotalPages = Convert.ToInt32(Session["TotalPages"]);
                if (CurrentPage - 1 <= 0)
                {
                    LinkButtonPrevious.Enabled = false;
                }
                else
                {
                    LinkButtonPrevious.Enabled = true;
                }

                if (CurrentPage < TotalPages - 1)
                {
                    LinkButtonNext.Enabled = true;
                }
                else
                {
                    LinkButtonNext.Enabled = false;
                }
                if (TotalPages > 1)
                {
                    LinkButtonLast.Enabled = true;
                    LinkButtonFirst.Enabled = true;
                }
                else
                {
                    LinkButtonLast.Enabled = false;
                    LinkButtonFirst.Enabled = false;
                }
            }
        }
        catch
        { }
    }

    protected void ButtonSeeMore_Click(object sender, EventArgs e)
    {
        Session["ContractId"] = ((Button)sender).CommandArgument.ToString();
        Response.Redirect(@"~\User\Shares\ProjectStatusDetails.aspx");
    }


    public void PopulateGrid(System.Security.Principal.IPrincipal thisUser)
    {
#region old Code
        //if (thisUser.Identity.IsAuthenticated)
        //{
        //    if (thisUser.IsInRole("admin")  
        //         || thisUser.IsInRole("employer") || thisUser.IsInRole("edituser") || thisUser.IsInRole("viewuser"))
        //    {
        //        List<Business.GridContractType> dataSource = new List<GridContractType>();

        //        dataSource = Business.ProjectDetails.GetProjectAllPaged(GridViewProjects.PageSize, Convert.ToInt32(Session["PageIndex"]),
        //                                                                                 true, true);

        //        GridViewProjects.DataSource = dataSource;
        //        Session["TotalPages"] =
        //            Business.ProjectDetails.GetTotalPageCountOfContracts(GridViewProjects.PageSize, true, true).ToString();
        //    }
        //    else if( thisUser.IsInRole("fourthfactor"))
        //    {
        //        List<Business.GridContractType> dataSource = new List<GridContractType>();

        //        dataSource = Business.ProjectDetails.GetProjectAllPagedFourthFactor(Membership.GetUser().ProviderUserKey,GridViewProjects.PageSize, Convert.ToInt32(Session["PageIndex"]),
        //                                                                                 true, true);

        //        GridViewProjects.DataSource = dataSource;
        //        Session["TotalPages"] =
        //            Business.ProjectDetails.GetTotalPageCountOfContracts(GridViewProjects.PageSize, true, true).ToString();
   
        //    }
        //    else if ( thisUser.IsInRole("bonyadshahrestan"))
        //    {
        //        IDataReader dr=DataAccess.TblUserDetail.FetchByParameter(DataAccess.TblUserDetail.Columns.UserId,Membership.GetUser().ProviderUserKey);
        //        dr.Read();
        //        Guid cityid=new Guid( dr["CityId"].ToString());
        //        dr.Close();
        //        List<Business.GridContractType> dataSource = new List<GridContractType>();

        //        dataSource = Business.ProjectDetails.GetProjectAllPagedshahrestan(cityid, GridViewProjects.PageSize, Convert.ToInt32(Session["PageIndex"]),
        //                                                                                 true, true);

        //        GridViewProjects.DataSource = dataSource;
        //        Session["TotalPages"] =
        //            Business.ProjectDetails.GetTotalPageCountOfContracts(GridViewProjects.PageSize, true, true).ToString();

        //    }
        //    else if (thisUser.IsInRole("advisor")
        //              || thisUser.IsInRole("Surveyor"))
        //    {
        //        var userId = new Guid(Membership.GetUser().ProviderUserKey.ToString());
        //        //GridViewProjects.AllowPaging = false;
        //        GridViewProjects.DataSource = Business.ProjectDetails.GetProjectByUserId(userId);
        //    }
        //    Page.DataBind();}
#endregion
        //DropDownList downList = (LoginViewSearch.FindControl("DropDownListSortAdvisor") as DropDownList);
        //RadioButton radioButtonAsc = new RadioButton();
        //radioButtonAsc.Checked = true;
        //RadioButton radioButtonDec = new RadioButton();
        bool advisorSearch = true;
        bool surveyorSearch = true;

        var userId = new Guid(Membership.GetUser().ProviderUserKey.ToString());
        var allProjects = new List<GridContractType>();

        if (!(thisUser.IsInRole("Advisor")
                      || thisUser.IsInRole("Surveyor")))
        {
            //downList = (LoginViewSearch.FindControl("DropDownListSort") as DropDownList);
            //radioButtonAsc = (LoginViewSearch.FindControl("RadioButtonAsc") as RadioButton);
            //radioButtonDec = (LoginViewSearch.FindControl("RadioButtonDec") as RadioButton);
            advisorSearch = (LoginViewSearch.FindControl("CheckBoxAdvisor") as CheckBox).Checked;
            surveyorSearch = (LoginViewSearch.FindControl("CheckBoxSurveyor") as CheckBox).Checked;
        }

        List<Business.GridContractType> dataSource = new List<GridContractType>();
        if (thisUser.Identity.IsAuthenticated)
        {
            #region Admin_employer
            if (thisUser.IsInRole("admin") || thisUser.IsInRole("employer") || thisUser.IsInRole("edituser") || thisUser.IsInRole("viewuser"))
            {
                dataSource = Business.ProjectDetails.GetProjectAllPaged(GridViewProjects.PageSize, Convert.ToInt32(Session["PageIndex"]),
                                                                                         advisorSearch, surveyorSearch);
            }
            #endregion

            #region FourthFactor
            else if (thisUser.IsInRole("fourthfactor"))
            {
                dataSource = Business.ProjectDetails.GetProjectAllPagedFourthFactor(Membership.GetUser().ProviderUserKey, GridViewProjects.PageSize, Convert.ToInt32(Session["PageIndex"]),
                                                                                         advisorSearch, surveyorSearch);
                
                GridViewProjects.DataSource = dataSource;
                Session["TotalPages"] =
                    Business.ProjectDetails.GetTotalPageCountOfContracts(GridViewProjects.PageSize, advisorSearch, surveyorSearch).ToString();
            }
            #endregion

            #region BonyadShahrestan
            else if (thisUser.IsInRole("bonyadshahrestan"))
            {
                dataSource = Business.ProjectDetails.GetProjectAllPagedFourthFactor(Membership.GetUser().ProviderUserKey, GridViewProjects.PageSize, Convert.ToInt32(Session["PageIndex"]),
                                                                                         advisorSearch, surveyorSearch);
            }
            #endregion

            #region advisor_Surveyor

            else if (thisUser.IsInRole("Advisor")
                      || thisUser.IsInRole("Surveyor"))
            {

                //GridViewProjects.AllowPaging = false;
                dataSource = Business.ProjectDetails.GetProjectByUserIdPaged(GridViewProjects.PageSize, Convert.ToInt32(Session["PageIndex"]), userId);
            }
            #endregion

            #region Asc_Dec Section

            //if (radioButtonAsc != null)
            //    if (radioButtonAsc.Checked)
            //    {
            //        if (downList != null)
            //            switch (Convert.ToInt32(downList.SelectedValue))
            //            {
            //                case 0:
            //                    dataSource = dataSource.OrderBy(project => project.VillageName).ToList();
            //                    break;
            //                case 1:
            //                    dataSource = dataSource.OrderBy(project => project.AdvisorFullName).ToList();
            //                    break;
            //                case 2:
            //                    dataSource = dataSource.OrderBy(project => project.ContractNumber).ToList();
            //                    break;
            //                case 3:
            //                    dataSource = dataSource.OrderBy(project => project.City).ToList();
            //                    break;
            //            }
            //    }
            //if (radioButtonDec != null)
            //    if (radioButtonDec.Checked)
            //    {
            //        if (downList != null)
            //            switch (Convert.ToInt32(downList.SelectedValue))
            //            {
            //                case 0:
            //                    dataSource = dataSource.OrderByDescending(project => project.VillageName).ToList();
            //                    break;
            //                case 1:
            //                    dataSource = dataSource.OrderByDescending(project => project.AdvisorFullName).ToList();
            //                    break;
            //                case 2:
            //                    dataSource = dataSource.OrderByDescending(project => project.ContractNumber).ToList();
            //                    break;
            //                case 3:
            //                    dataSource = dataSource.OrderByDescending(project => project.City).ToList();
            //                    break;
            //            }
            //    }
            #endregion

            if (thisUser.IsInRole("advisor") || thisUser.IsInRole("surveyor"))
            {
                allProjects = Business.ProjectDetails.GetProjectByUserId(userId);
                Session["TotalPages"] = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(allProjects.Count) / Convert.ToDouble(GridViewProjects.PageSize)));
            }
            else
            {
                Session["TotalPages"] =
                Business.ProjectDetails.GetTotalPageCountOfContracts(GridViewProjects.PageSize, advisorSearch, surveyorSearch).ToString();
            }

            GridViewProjects.DataSource = dataSource;

            Page.DataBind();
        }  
    }

    protected void LinkButtonNext_Click(object sender, EventArgs e)
    {
        var thisUser = HttpContext.Current.User;
        if (LinkButtonNext.Enabled)
        {
            if ((Convert.ToInt32(Session["PageIndex"])) + 1 < Convert.ToInt32(Session["TotalPages"]))
            {
                Session["PageIndex"] = (Convert.ToInt32(Session["PageIndex"])) + 1; 
            }
            
            PopulateGrid(thisUser);
        }
    }

    protected void LinkButtonPrevious_Click(object sender, EventArgs e)
    {
        var thisUser = HttpContext.Current.User;
        if (LinkButtonPrevious.Enabled)
        {
            if((Convert.ToInt32(Session["PageIndex"])) -1 >= 0)
            {
                Session["PageIndex"] = (Convert.ToInt32(Session["PageIndex"])) - 1;
            }
            PopulateGrid(thisUser);
        }
    }


    protected void LinkButtonFirst_Click(object sender, EventArgs e)
    {
        var thisUser = HttpContext.Current.User;
        Session["PageIndex"] = 0;
        PopulateGrid(thisUser);
    }

    protected void LinkButtonLast_Click(object sender, EventArgs e)
    {
        var thisUser = HttpContext.Current.User;
        Session["PageIndex"] = Convert.ToInt32(Session["TotalPages"]) - 1;
        PopulateGrid(thisUser);
    }

    protected void GridViewProjects_PreRender(object sender, EventArgs e)
    {

        try
        {
            var thisUser = HttpContext.Current.User;
            if (thisUser.Identity.IsAuthenticated)
            {
                if ( thisUser.IsInRole( "admin" ) || thisUser.IsInRole( "fourthfactor" ) || thisUser.IsInRole( "bonyadshahrestan" )
                     || thisUser.IsInRole( "employer" ) )
                {
                    if ( GridViewProjects.AllowPaging )
                        GridViewProjects.BottomPagerRow.Visible = true;
                }
                else if ( thisUser.IsInRole( "advisor" )
                          || thisUser.IsInRole( "Surveyor" ) )
                {
                    if (GridViewProjects.AllowPaging)
                        GridViewProjects.BottomPagerRow.Visible = true;
                }
            }
        }
        catch (Exception ex)
        {
            
        }
    }

    protected void GridViewProjects_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType
             == DataControlRowType.DataRow)
        {
            if (e.Row.RowIndex % 2 == 0)
            {
                e.Row.BackColor = System.Drawing.Color.AliceBlue;
            }
        }
        if (e.Row.RowType
             == DataControlRowType.Pager)
        {
            e.Row.BackColor = System.Drawing.Color.FromArgb(0x61, 0x84, 0xC3);
            UpdatePanel updatePanel = e.Row.Cells[0].FindControl("UpdatePanelFooter") as UpdatePanel;
            Label lbl = updatePanel.FindControl("LabelPageNumber") as Label;
            if (lbl != null)
                lbl.Text = string.Format("{0} از {1} صفحه ",Convert.ToInt32(Session["PageIndex"])+1, Session["TotalPages"]);
        }
    }

    protected void SelectContract_Click(object sender )
    {
        Session["ContractId"] = SelectContract1.Contractid.ToString();
        Response.Redirect(@"~\User\Shares\ProjectStatusDetails.aspx");
    }
}